package com.cl.cloud.binlog.util;

import cn.hutool.core.codec.Base64;
import lombok.extern.slf4j.Slf4j;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;

/**
 * @description:
 * @author: liuzijian
 * @time: 2021-12-21 15:37
 */
@Slf4j
public class StringConverter {

    private static Set<String> dateTypeSet = new HashSet<>();

    static {
        dateTypeSet.add("DATETIME");
        dateTypeSet.add("TIMESTAMP");
    }

    public static String convert(Object from, String type) {
        if (from == null) {
            return "";
        }
        if (dateTypeSet.contains(type)) {
            return LocalDateTime.ofEpochSecond((Long) from / 1000, 0, ZoneOffset.ofHours(0)).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        }

        if (Objects.equals(type, "DATE")) {
            return LocalDateTime.ofEpochSecond((Long) from / 1000, 0, ZoneOffset.ofHours(0)).format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        }

        if (from.getClass() == byte[].class && !"MEDIUMBLOB".equals(type)) {
            return new String((byte[]) from);
        }
        if (from.getClass() == byte[].class && "MEDIUMBLOB".equals(type)) {
            return Base64.encode(new String((byte[]) from));
        }
        return String.valueOf(from);
    }

}
